package com.spsy.pay.controller;

import com.alibaba.fastjson.JSON;
import com.spsy.api.order.OrderApi;
import com.spsy.common.core.domain.R;
import com.spsy.pay.domain.PaymentOrder;
import com.spsy.pay.enums.OrderStatusEnum;
import com.spsy.pay.mq.vo.OrderMqVo;
import com.spsy.pay.order.CommUtil;
import com.spsy.pay.order.Constants;
import com.spsy.pay.order.XMLUtil;
import com.spsy.pay.service.IPaymentOrderService;
import com.spsy.pay.vo.WeixinNotifyVo;
import com.spsy.vo.NotifyPay2OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * @author: liuzhiping
 * @date: 2024/12/12 21:35
 **/
@RestController
@Slf4j
@CrossOrigin
@RequestMapping(value = "/pay")
public class WeixinPayNotifyController {
    @Autowired
    private IPaymentOrderService iPaymentOrderService;
    @Resource
    private OrderApi orderApi;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostMapping(value = "/weixin/notifyTest", consumes = MediaType.APPLICATION_JSON_VALUE)
    public R createOrder(@RequestBody WeixinNotifyVo weixinNotifyVo) throws Exception {
        log.info("weixinNotifyVo:{}", JSON.toJSONString(weixinNotifyVo));
        if (weixinNotifyVo.getReturnCode().equals("success")) {
            int updateCount = this.iPaymentOrderService.updatePaymentOrderByOrderId(PaymentOrder.builder().orderNo(weixinNotifyVo.getOrderId()).orderStatus(OrderStatusEnum.PAYED.getValue()).build());
            log.info("updateCount:{}", updateCount);
            NotifyPay2OrderVo notifyPay2OrderVo = new NotifyPay2OrderVo();
            notifyPay2OrderVo.setOrderId(weixinNotifyVo.getOrderId());
            notifyPay2OrderVo.setStatus(2);
            this.orderApi.createOrder(notifyPay2OrderVo);
            return R.ok();
        } else {
            return R.fail("fail");
        }
    }

    @RequestMapping(value = "weixin/notify", method = RequestMethod.POST, produces = {"application/xml; charset=UTF-8"})
    public void asyncNotifyFromWx(HttpServletRequest request, HttpServletResponse response) {
        String uuid = "2302a-1234567890";
        long start = System.currentTimeMillis();
        int retunCode = 0;
        String msg = "";
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = request.getReader();
            String str = "";
            while ((str = reader.readLine()) != null) {
                builder.append(str);
            }
            log.info("====notify wx 微信回调2302a【开始】 uuid={},data={}", uuid, builder.toString());
            Map<String, String> map = XMLUtil.doXMLParse(builder.toString());
            log.info("====notify wx2302a 微信结果【结束】 map={}", JSON.toJSONString(map));
            String weixinSign = map.get("sign");
            String selfSign = CommUtil.genSign(map, Constants.API_KEY, "MD5");
            String orderNo = map.get("out_trade_no");
            log.info("----------123456 orderNo:{} ", orderNo);
            String resultCode = map.get("result_code");
            String returnCode = map.get("return_code");
            if (resultCode.toUpperCase().equals("SUCCESS") && returnCode.toUpperCase().equals("SUCCESS")) {
                List<PaymentOrder> list = this.iPaymentOrderService.selectPaymentOrderList(PaymentOrder.builder().orderNo(orderNo).build());
                if (null != list && list.size() >= 1) {
                    PaymentOrder paymentOrder = list.get(0);
                    if (paymentOrder.getOrderStatus().intValue() != OrderStatusEnum.PAYED.getValue()) {
                        OrderMqVo orderMqVo = OrderMqVo.builder().orderId(orderNo).status("2").build();
//                        this.rabbitTemplate.convertAndSend(RabbitmqConstant.MQ_EXCHANGE, RabbitmqConstant.MQ_ROUTTING, com.alibaba.fastjson2.JSON.toJSONString(orderMqVo));
                        System.out.println("222222222222");
                    }
                }
            }
            retunCode = 200;
            msg = "成功";
        } catch (Exception e) {
            msg = "回调处理失败";

        }
        PrintWriter out = null;
        try {
            String returnCode = retunCode == 200 ? "SUCCESS" : "FAIL";
            builder = new StringBuilder();
            response.setContentType("text/xml;charset=utf-8");
            out = response.getWriter();
            builder.append("<xml>\n");
            builder.append("  <return_code><![CDATA[" + returnCode + "]]></return_code>\n");
            builder.append("	<return_msg><![CDATA[" + msg + "]]></return_msg>\n");
            builder.append("</xml>\n");
            log.info("=====返回数据 sb={}", builder.toString());
            out.write(builder.toString());
            out.flush();
        } catch (IOException e) {
            log.error("=====notify->from->wx error(" + uuid + "):" + e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (out != null) {
                out.close();
            }
            log.info("=====notify->from->wx end(" + uuid + "):" + (System.currentTimeMillis() - start));
        }
    }
}